package sz.szsmk.citizencard.ui.activity;

import android.annotation.SuppressLint;
import android.app.Dialog;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.TextView;

import androidx.annotation.NonNull;

import com.chenenyu.router.annotation.Route;
import com.google.gson.Gson;
import com.youzan.androidsdk.YouzanSDK;

import java.io.File;
import java.math.BigDecimal;

import sz.szsmk.citizencard.DaggerApplication;
import sz.szsmk.citizencard.R;
import sz.szsmk.citizencard.model.network.bean.SetJson;
import sz.szsmk.citizencard.databinding.SettingActivityBinding;
import sz.szsmk.citizencard.dialog.SuccessDialog;
import sz.szsmk.citizencard.ioc.Compontent.DaggerCommonActivityComponent;
import sz.szsmk.citizencard.mvp.contract.ISettingContact;
import sz.szsmk.citizencard.mvp.presenter.SettingPresenter;
import sz.szsmk.citizencard.ui.base.IBaseActivity;
import sz.szsmk.citizencard.util.ACache;
import sz.szsmk.citizencard.util.Constant;
import sz.szsmk.citizencard.util.DataCleanManager;
import sz.szsmk.citizencard.util.DataStoreUtils;
import sz.szsmk.citizencard.util.JumpThirdView;
import sz.szsmk.citizencard.util.JumpUtils;

/**
 * Copyright (c)2018
 * author: zdh
 * created on: 2018/6/21 15:18
 * description:
 */
@Route("setting")
public class SettingActivity extends IBaseActivity<SettingPresenter, SettingActivityBinding>
        implements ISettingContact.ISettingView, View.OnClickListener {

    private View inflate;
    private TextView choosePhoto;
    private TextView takePhoto;
    private Dialog dialog;
    private String access_token;
    @SuppressLint("HandlerLeak")

    @Override
    protected int attachLayoutRes() {
        return R.layout.setting_activity;
    }

    @Override
    protected void initInjector() {
        DaggerCommonActivityComponent.builder().appCompontent(DaggerApplication.getAppComponent())
                .build().inject(this);

    }

    @Override
    protected void initViews() {

        dataBinding.titleLayout.settingTitle.setText("设置");
        dataBinding.titleLayout.back.setOnClickListener(this);
        dataBinding.setRlCache.setOnClickListener(this);
        dataBinding.setRlAboutUs.setOnClickListener(this);
        dataBinding.setRlNotice.setOnClickListener(this);
        dataBinding.setRlOption.setOnClickListener(this);
        dataBinding.setRlPraise.setOnClickListener(this);
        dataBinding.setRlRecommend.setOnClickListener(this);
        dataBinding.setRlSelf.setOnClickListener(this);
        dataBinding.btnLogout.setOnClickListener(this);
        dataBinding.setRlPrivacy.setOnClickListener(this);
        dataBinding.setRlAgreement.setOnClickListener(this);

        access_token = ACache.get(this).getAsString("access_token");
        if (access_token != null) {
            dataBinding.btnLogout.setVisibility(View.VISIBLE);
        } else {

            dataBinding.btnLogout.setVisibility(View.GONE);
        }


        if(ACache.get(DaggerApplication.getIns()).getAsObject("NewMessageReminder") !=null){
            Boolean bo = (Boolean) ACache.get(DaggerApplication.getIns()).getAsObject("NewMessageReminder");
            dataBinding.swNewMessageReminder.setChecked( bo);
        }else{
            dataBinding.swNewMessageReminder.setChecked(true);
            ACache.get(DaggerApplication.getIns()).put("NewMessageReminder", true);
        }
        dataBinding.swNewMessageReminder.setOnCheckedChangeListener((buttonView, isChecked) ->
                ACache.get(DaggerApplication.getIns()).put("NewMessageReminder", isChecked));

//        showCache();
        getCacheSize();
    }

    private void showCache() {
        String strRand = "";
        for (int i = 0; i < 1; i++) {
            strRand += String.valueOf((int) (Math.random() * 10));
        }
        dataBinding.settingCache.setText(strRand);

//        Log.d("debug", "Rand = " + strRand);

    }

    @Override
    protected void updateViews() {

    }

    @Override
    public void getDataFaile() {

    }

    @Override
    public void loginOutSucc() {

    }

    @Override
    public void loginOutFail() {

    }

    public static long getFolderSize(File file) {
        long size = 0;
        try {
            File[] fileList = file.listFiles();
            for (int i = 0; i < fileList.length; i++) {
                // 如果下面还有文件
                if (fileList[i].isDirectory()) {

                    size = size + getFolderSize(fileList[i]);
                } else {
                    size = size + fileList[i].length();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return size;
    }

    public void getCacheSize() {  //获取内存的大小
        long cacheSize = getFolderSize(getCacheDir());
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            cacheSize += getFolderSize(getExternalCacheDir());
        }
        try {
            dataBinding.setCache.setText(getFormatSize(cacheSize).toString());//将获取到的大小set进去
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    public static String getFormatSize(double size) throws Exception {

        double kiloByte = size / 1024;
        if (kiloByte < 1) {
            return size + "Byte";
        }

        double megaByte = kiloByte / 1024;
        if (megaByte < 1) {
            BigDecimal result1 = new BigDecimal(Double.toString(kiloByte));
            return result1.setScale(2, BigDecimal.ROUND_HALF_UP)
                    .toPlainString() + "KB";
        }

        double gigaByte = megaByte / 1024;
        if (gigaByte < 1) {
            BigDecimal result2 = new BigDecimal(Double.toString(megaByte));
            return result2.setScale(2, BigDecimal.ROUND_HALF_UP)
                    .toPlainString() + "MB";
        }

        double teraBytes = gigaByte / 1024;
        if (teraBytes < 1) {
            BigDecimal result3 = new BigDecimal(Double.toString(gigaByte));
            return result3.setScale(2, BigDecimal.ROUND_HALF_UP)
                    .toPlainString() + "GB";
        }
        BigDecimal result4 = new BigDecimal(teraBytes);
        return result4.setScale(2, BigDecimal.ROUND_HALF_UP).toPlainString()
                + "TB";
    }


    @Override
    public void onClick(View v) {
        int id = v.getId();
        if (id == R.id.set_rl_about_us) {
            JumpUtils.jump(this, "about", 0);
        } else if (id == R.id.set_rl_cache) {
            DataCleanManager.cleanInternalCache(SettingActivity.this);
            DataCleanManager.cleanDatabases(SettingActivity.this);
            DataCleanManager.cleanSharedPreference(SettingActivity.this);
            dataBinding.setCache.setText("0.0MB");
            final SuccessDialog dialog = new SuccessDialog(this, "操作成功");
            dialog.show();
            new Thread() {
                @Override
                public void run() {
                    super.run();
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    dialog.cancel();
                }
            }.start();
        } else if (id == R.id.set_rl_notice) {
            JumpUtils.jump(this, "setNotice", 0);
        } else if (id == R.id.set_rl_option) {
            if (access_token != null) {
                JumpUtils.jump(this, "suggest", 0);
            } else {
                JumpUtils.jump(this, "login", 0);
            }
        } else if (id == R.id.set_rl_praise) {//                PubUtils.popTipOrWarn(this, "上个好评");
            Uri uri = Uri.parse("market://details?id=" + getPackageName());
            Intent intent = new Intent(Intent.ACTION_VIEW, uri);
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            startActivity(intent);
        } else if (id == R.id.set_rl_recommend) {
            showShareDialog();
        } else if (id == R.id.set_rl_self) {
            if (access_token != null) {
                JumpUtils.jump(this, "idsafe", 0);
            } else {
                JumpUtils.jump(this, "login", 0);
            }
        } else if (id == R.id.back) {
            finish();
        } else if (id == R.id.btn_logout) {
            DataStoreUtils.INSTANCE.isLogin().setValue(false);
            ACache.get(this).remove("userinfo");
            ACache.get(this).remove("access_token");
            Constant.EXTENT = "";
            ACache.get(this).remove("mextend");
            ACache.get(this).remove("userId");
            ACache.get(DaggerApplication.getIns()).remove("login_type");
            YouzanSDK.userLogout(getApplicationContext());
            //退出登陆，用户主动退出登陆状态的时候，可以通过该接口和 SDK 同步登陆状态
//                TransitUI.logout();
            finish();
        } else if (id == R.id.set_rl_privacy) {//隐私政策
            Bundle bundle = new Bundle();
            bundle.putString("url", Constant.BASE_URL + "app-front-end/#/common/secretAgreement?isMain=1");
            JumpUtils.jumptoNatvie(this, "webView", 0, bundle);
        } else if (id == R.id.set_rl_agreement) {//用户协议
            Bundle bundle1 = new Bundle();
            bundle1.putString("url", Constant.BASE_URL + "app-front-end/#/common/serviceAgreement");
            JumpUtils.jumptoNatvie(this, "webView", 0, bundle1);
        }
    }

    private void showShareDialog() {
        dialog = new Dialog(this, R.style.ActionSheetDialogStyle);
        inflate = LayoutInflater.from(this).inflate(R.layout.dialog_layout, null);
        //初始化控件
        choosePhoto = (TextView) inflate.findViewById(R.id.choosePhoto);
//        takePhoto = (TextView) inflate.findViewById(R.id.takePhoto);
        choosePhoto.setOnClickListener(this);
//        takePhoto.setOnClickListener(this);
        //将布局设置给Dialog
        dialog.setContentView(inflate);
        //获取当前Activity所在的窗体
        Window dialogWindow = dialog.getWindow();
        //设置Dialog从窗体底部弹出
        dialogWindow.setGravity(Gravity.BOTTOM);
        //获得窗体的属性
        WindowManager.LayoutParams lp = dialogWindow.getAttributes();
        lp.y = 20;//设置Dialog距离底部的距离
//       将属性设置给窗体
        dialogWindow.setAttributes(lp);
        dialog.show();//显示对话框
    }
}
